//
//  ZWYNetTool.m
//  Magic-C
//
//  Created by 赵五一 on 16/7/13.
//  Copyright © 2016年 赵五一. All rights reserved.
//

#import "ZWYNetTool.h"
#import "AFNetworking.h"

@interface ZWYNetTool()
//@property (nonatomic, assign) BOOL cache;
@property (nonatomic, copy) NSString *cache;
@end
@implementation ZWYNetTool

+(void)GET:(NSString *)url
   andBody:(id)body
 andHeader:(NSDictionary *)headers
andResponse:(ZWYResponseStyle)responseStyle
andSuccessBlock:(successBlock)success
andFailureBlock:(failureBlock)failure
{

    // 寻找路径
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
//    NSLog(@"%@", documentPath);
    // 文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *LCOnePsychologyCaches = [documentPath stringByAppendingPathComponent:@"LCOnePsychologyCaches"];
    BOOL resultFile = [fileManager createDirectoryAtPath:LCOnePsychologyCaches withIntermediateDirectories:YES attributes:nil error:nil];
    if (resultFile) {
//        NSLog(@"创建缓存文件夹成功");
    }
    // 拼接缓存路径
    
    NSString *path = [NSString stringWithFormat:@"%ld.plist", (unsigned long) [url hash]];
    NSString *textFilePath = [LCOnePsychologyCaches stringByAppendingPathComponent:path];
//    NSLog(@"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000:%@", textFilePath);
    // 1. 设置网络管理者
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    // 2. 设置请求头
    
    if (headers) {
        
        for (NSString *key in headers.allKeys) {
            
            [manager.requestSerializer setValue:headers[key] forHTTPHeaderField:key];
            
        }
    }
    
    // 3. 设置返回数据的类型
    switch (responseStyle) {
        case ZWYJSON:
            manager.responseSerializer = [AFJSONResponseSerializer serializer];
            break;
        case ZWYXML:
            manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
            break;
        case ZWYDATA:
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            break;
            
        default:
            break;
    }
    
    // 4. 设置响应数据类型
    
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", @"application/javascript",@"image/jpeg", @"text/vnd.wap.wml", @"text/xml", nil]];
    
    
    // 5. UTF-8转码
    
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    
    // 6. 使用AFN进行网络请求
    
    [manager GET:url parameters:body progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (responseObject) {
            // 归档
            [NSKeyedArchiver archiveRootObject:responseObject toFile:textFilePath];
            if ([NSKeyedArchiver archiveRootObject:responseObject toFile:textFilePath]) {
//                NSLog(@"写入成功");
                
            } else {
//                NSLog(@"写入失败");
            }
            success(responseObject);
            
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        if (error) {
            failure(error);
//            // 解档
//            success([NSKeyedUnarchiver unarchiveObjectWithFile:textFilePath]);
        }
    }];
    AFNetworkReachabilityManager *networkJudge = [AFNetworkReachabilityManager sharedManager];
    
    [networkJudge startMonitoring];
    
    [networkJudge setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if (status == AFNetworkReachabilityStatusNotReachable ){
            if (textFilePath) {
                success([NSKeyedUnarchiver unarchiveObjectWithFile:textFilePath]);
            }
        }
    }];
}


+(void)POST:(NSString *)url andBody:(id)body andBodyStyle:(ZWYRequestStyle)bodyStyle andHeader:(NSDictionary *)headers andResponse:(ZWYResponseStyle)responseStyle andSuccessBlock:(successBlock)success andFailureBlock:(failureBlock)failure
{
    // 1. 设置网络管理者
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    
    // 2. 设置body的数据类型
    
    switch (bodyStyle) {
        case ZWYBodyJSON:
            
            manager.requestSerializer = [AFJSONRequestSerializer serializer];
            
            break;
            
        case ZWYBodyString:
            
            [manager.requestSerializer setQueryStringSerializationWithBlock:^NSString * _Nonnull(NSURLRequest * _Nonnull request, id  _Nonnull parameters, NSError * _Nullable * _Nullable error) {
                
                return parameters;
                
            }];
            
            break;
            
        default:
            break;
    }
    
    // 3. 设置请求头
    
    if (headers) {
        
        for (NSString *key in headers.allKeys) {
            
            [manager.requestSerializer setValue:headers[key] forHTTPHeaderField:key];
            
        }
    }
    
    // 3. 设置返回数据的类型
    switch (responseStyle) {
        case ZWYJSON:
            manager.responseSerializer = [AFJSONResponseSerializer serializer];
            break;
        case ZWYXML:
            manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
            break;
        case ZWYDATA:
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            break;
            
        default:
            break;
    }
    
    // 4. 设置响应数据类型
    
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", @"application/javascript",@"image/jpeg", @"text/vnd.wap.wml", nil]];
    
    
    // 5. UTF-8转码
    
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    
    // 6. 使用AFN进行网络请求
    
    [manager POST:url parameters:body progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (responseObject) {
            success(responseObject);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (error) {
            failure(error);
        }
        
    }];

}






@end
